'use strict';

const BaseService = require('../../base');
const {
    getDeptWhere
} = require("../../../../utils/tools");
const Op = require('sequelize').Op

class Service extends BaseService {
    constructor(...tag) {
        super(...tag)
        this.modelName = 'Users'
    }
    // 查询, 传页面，分页返回，否则全部返回
    async findList(query, order = [
        ['createdAt', 'DESC']
    ]) {
        let obj = {
            where: {},
            order,
            include: [{
                model: this.ctx.model['Departments']
            }]
        }
        if (query.offset) {
            query.limit = query.limit ? query.limit : 10
            query.offset = (query.offset - 1) * query.limit
            obj.limit = query.limit
            obj.offset = query.offset
        } else {
            obj.limit = null
            obj.offset = null
        }
        for (let key in query) {
            if (key !== 'limit' && key !== 'offset') {
                if (key === 'deptId') {
                    obj.where[key] = getDeptWhere(this.ctx, {
                        deptId: query.deptId
                    }).deptId
                } else {
                    obj.where[key] = {
                        // 模糊查询
                        [Op.like]: '%' + query[key] + '%'
                    }
                }
            }
        }

        return await this.ctx.model[this.modelName].findAndCountAll(obj);
    }
    // 查询单个
    async findOne(id) {
        return await this.ctx.model[this.modelName].findOne({
            where: {
                id
            },
            include: [{
                model: this.ctx.model['Roles'],
                as: 'roles'
            }]
        })
    }
    // 添加用户
    async create(query) {
        try {
            // 建立事务对象
            let transaction = await this.ctx.model.transaction();
            let user = await this.ctx.model.Users.create(query,{transaction});
            let roleIds = this.ctx.request.body['roleIds']
            let obj = {userId: user.id,roleId: roleIds}
            await this.ctx.model.UserRole.create(obj,{transaction});
            await transaction.commit();
            return true
        } catch (error) {
            if (error.name = 'SequelizeUniqueConstraintError') {
                this.ctx.throw(500, '用户名已存在')
            } else {
                this.ctx.throw(500, '服务器错误')
            }
        }
    }
    // 修改密码
    async resetPwd(query, id) {
        try {
            return await this.ctx.model[this.modelName].update(query, {
                where: {
                    id
                }
            })
        } catch (error) {
            ctx.throw(500, '数据口修改数据将')
        }
    }
    // 删除用户
    async destroy(ids){
        let transaction;
        try {
            transaction = await this.ctx.model.transaction();
            await this.ctx.model[this.modelName].destroy({
                where:{
                    id:{
                        [Op.or]:ids
                    }
                },
                transaction
            })
            
            await this.ctx.model.UserRole.destroy({
                where:{
                    id:{
                        [Op.or]:ids
                    }
                },
                transaction
            })
            await transaction.commit();
            return true

        } catch (error) {
            this.ctx.throw(500, '服务器错误') 
        }

    }
    // 修改用户
    async update(query,id){
        const { ctx } = this;
        let transaction;
        try {
            transaction = await this.ctx.model.transaction();
            await ctx.model[this.modelName].update(query,{
                where:{
                    id:id
                },
                transaction
            })
            await this.ctx.model.UserRole.destroy({
                where: {
                  userId: id
                },
                transaction
            })
            let roleIds = this.ctx.request.body['roleIds']
            let obj = {userId: user.id,roleId: roleIds}
            await this.ctx.model.UserRole.create(obj,{transaction});
            await transaction.commit();
            return true
        } catch (error) {
            if (error.name === 'SequelizeUniqueConstraintError') {
                this.ctx.throw(500, '用户名已经被占用') 
              } else {
                this.ctx.throw(500, '服务器错误') 
              }
        }
    }
}

module.exports = Service;